package cn.iocoder.yudao.module.promotion.redpacket.dao;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.dao.mapper.CoreMapper;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreLambdaQueryWrapper;
import cn.iocoder.yudao.module.api.trade.scan.dto.ScanOrderDTO;
import cn.iocoder.yudao.module.promotion.redpacket.pojo.po.RedPacketUsed;
import org.apache.ibatis.annotations.Mapper;

import javax.annotation.Nullable;
import java.util.List;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * Mapper 接口
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/07/26
 */
@Mapper
public interface RedPacketUsedMapper extends CoreMapper<RedPacketUsed> {

    default int sumUsedAmount(Long userId, @Nullable Long shopId) {
        CoreLambdaQueryWrapper<RedPacketUsed> wrapper = new CoreLambdaQueryWrapper<>();
        wrapper.select(RedPacketUsed::getDeductPrice);
        wrapper.eq(RedPacketUsed::getUserId, userId);
        wrapper.eqIfPresent(RedPacketUsed::getShopId, shopId);
        List<RedPacketUsed> list = selectList(wrapper);
        if (CollUtil.isEmpty(list)) {
            return 0;
        }
        return list.stream().mapToInt(RedPacketUsed::getDeductPrice).sum();
    }

    default boolean insertIfNecessary(ScanOrderDTO order) {
        CoreLambdaQueryWrapper<RedPacketUsed> wrapper = new CoreLambdaQueryWrapper<>();
        wrapper.eq(RedPacketUsed::getTradeNo, order.getTradeNo());
        RedPacketUsed redPacketUsed = selectOne(wrapper);
        if (redPacketUsed != null) {
            return false;
        }
        redPacketUsed = new RedPacketUsed();
        redPacketUsed.setUserId(order.getUserId());
        redPacketUsed.setShopId(order.getShopId());
        redPacketUsed.setTradeNo(order.getTradeNo());
        redPacketUsed.setOrderPrice(order.getOriginPrice());
        redPacketUsed.setDeductPrice(order.getRedpacketDeductPrice());
        redPacketUsed.setRemark(order.getNote());
        return insert(redPacketUsed) > 0;
    }

}
